package com.yuri.news.controller;

import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yuri.news.domain.Pages;
import com.yuri.news.domain.Result;
import com.yuri.news.entity.User;
import com.yuri.news.jpa.RoleRepository;
import com.yuri.news.service.RoleService;
import com.yuri.news.service.UserService;
import com.yuri.news.tool.Tool;

/**
 * 用户控制器
 * 
 * @author Yuri
 *
 */

// 允许跨域请求
@CrossOrigin
// 以json形式返回
@ResponseBody
// 控制器
@Controller
@SuppressWarnings("deprecation")
public class UserController {
	
	private final Logger logger = LoggerFactory.getLogger(UserController.class);
	// 依赖注入
	@Autowired
	UserService userService;
	// 依赖注入
	@Autowired
	RoleService roleService; 
	@Autowired
	RoleRepository roleRepository;
	/**
	 * 根据用户名和密码进行查询
	 * 
	 * @param userName	用户名
	 * @param userPw	用户密码
	 * @return
	 */
	@RequestMapping(value = "findByNamePw", method = RequestMethod.POST)
	public Result<User> findByNameAndPw(String userName, String userPw) {
		// 日志打印
		logger.info("\n 根据用户名和密码进行查询(findByNamePw)开始: userName = " + userName + "\nuserPw = " + userPw);
		Result<User> result = new Result<User>();
		try {
			//
			List<User> users = new ArrayList<>();
			// 调用接口查询
			User user = userService.findByUserNameAndPw(userName, userPw);
			// 如果没有查询到用户信息
			if(user != null) {
				if(user.getIsAvailable()) {
					users.add(user);
					
					result.setData(users);
					result.setSuccess("查询成功");
				}else {
					result.setError("用户被禁用！请联系管理员");
				}
				
			}else {
				result.setError("无此用户信息！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setError("查询发生异常！");
		}
		
		logger.info("\n 根据用户名和密码进行查询(findByNamePw)结束: result = " + result);
		
		return result;
	}

	/**
	 * 添加用户
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "addUser", method = RequestMethod.POST)
	public Result<User> addUser(User user, String roleId) {
		logger.info("\n a添加用户（addUser）开始:User = " + user.toString());
		Result<User> result = new Result<>();
		
		try {
			if(userService.addUser(user, roleId)) {
				result.setSuccess("添加成功！");
			}else {
				result.setError("已经存在此用户");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setError("发生异常错误！");
		}
		
		logger.info("\n 添加用户（addUser）结束:result = " + result);
		return result;
	}

	/**
	 * 根据用户id设置用户的可用状态
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "setAvailable", method = RequestMethod.PUT)
	public Result<User> setAvailable(Long id) {
		logger.info("\n 根据用户id设置用户的可用状态(setAvailable)开始: User.id = " + id);
		Result<User> result = new Result<>();
		
		try {
			if (userService.setAvailable(id)) {
				result.setSuccess("修改成功！");
			} else {
				result.setError("无此用户信息！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setError("发生异常错误！");
		}
		
		logger.info("\n 根据用户id设置用户的可用状态(setAvailable)结束: result = " + result);
		return result;
	}

	/**
	 * 根据用户id查询用户
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "findUserById", method = RequestMethod.GET)
	public Result<User> findUserById(Long id) {
		logger.info("\n 根据用户id查询用户(findUserById)开始: User.id = " + id);
		Result<User> result = new Result<>();
		try {
			List<User> users = new ArrayList<>();
			// 查询用户
			User user = userService.findUserById(id);
			// 判断是否存在
			if(user != null) {
				users.add(user);
				
				result.setData(users);
				result.setSuccess("查询成功！");
			}else {
				result.setError("无此用户信息！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setError("发生异常！");
		}
		logger.info("\n 根据用户id查询用户(findUserById)结束: result = " + result);
		return result;
	}

	/**
	 * 更新用户信息
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "updateUser", method = RequestMethod.PUT)
	public Result<User> updateUser(User user) {
		
		logger.info("\n 更新用户信息：user:" + user.toString());
		Result<User> result = new Result<>();
		try {
			if(userService.updateUser(user)) {
				result.setSuccess("更新成功！");
			}else {
				result.setError("无此用户！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setError("发生异常错误！");
		}
		logger.info("\n 更新用户信息结束：result:" + result.toString());
		return result;
	}

	/**
	 * 给用户添加角色
	 * @param userId	用户id
	 * @param roleId	角色id
	 * @return
	 */
	@RequestMapping(value = "userAddRole", method = RequestMethod.POST)
	public Result<User> userAddRole(Long userId, Long roleId) {
		logger.info("\n 给用户添加角色（userAddRole）开始 userId = " + userId + "   roleId=" + roleId);
		Result<User> result = new Result<>();
		try {
			if(userService.userAddRole(userId, roleId)) {
				result.setSuccess("添加成功！");
			}else {
				result.setError("无此用户！");
			}
		} catch (Exception e) {
			result.setError("此权限已经存在");
		}
		logger.info("\n 给用户添加角色（userAddRole）结束 result = " + result);
		return result;
	}

	/**
	 * 删除用户角色
	 */
	@RequestMapping(value = "userDelRole", method = RequestMethod.DELETE)
	public Result<User> userDelRole(Long userId, Long roleId) {
		logger.info("\n 删除用户角色（userDelRole）开始 userId = " + userId + "   roleId=" + roleId);
		Result<User> result = new Result<>();
		try {
			if(userService.delRole(userId, roleId)) {
				result.setSuccess("删除成功！");
			}else {
				result.setError("删除失败！无此用户");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setError("发生异常错误！");
		}
		logger.info("\n 删除用户角色（userDelRole）结束 result = " + result);
		return result;
	}
	
	/**
	 * 查询所有用户
	 * @param isAva			是否可用
	 * @param page			当前页
	 * @param size			每页长度
	 * @return
	 */
	@RequestMapping(value = "findUserAll", method = RequestMethod.GET)
	public Result<User> findUserAll(
			@RequestParam(name = "isAva", defaultValue="true") Boolean isAva,
			@RequestParam(name = "page",defaultValue="0") Integer page,
			@RequestParam(name = "size", defaultValue="10") Integer size) {
		logger.info("\n 查询所有用户（findUserAll）开始：page：" + page+"\t size"+size);
		// 用户返回信息
		Result<User> result = new Result<>();
		try {
			Order order 	= new Order(Direction.ASC, "id"); // 根据字段id进行升序排序
			PageRequest pageRequest = PageRequest.of(page, size, new Sort(order));// 分页排序查询
			
			Page<User> users = null;
			users = userService.findUserAll(pageRequest, isAva);
			
			if(0 == users.getContent().size()) {
				result.setCode(-1);
				result.setMsg("数据库暂时无数据！请稍后再试");
			}else {
				Pages pages = new Pages(page, users.getTotalElements(), size);
				result.setPages(pages);
				result.setData(users.getContent());
				result.setSuccess("查询成功！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setError("发生异常错误！");
		}
		
		logger.info("\n 查询所有用户（findUserAll）结束：result：" + result);
		return result;
	}

	/**
	 * 关键字查询
	 * @param key		关键字
	 * @param isAva		是否为可用
	 * @param page		当前页数
	 * @param longth	显示条数
	 * @return
	 */
	@RequestMapping(value = "findUserByKey", method = RequestMethod.GET)
	public Result<User> findUserByKey(
			@RequestParam(name = "isAva", defaultValue="true") Boolean isAva,
			@RequestParam(name = "key", defaultValue="") String key,
			@RequestParam(name = "page",defaultValue="0") Integer page,
			@RequestParam(name = "size", defaultValue="10") Integer size) {
		logger.info("\n 关键字查询（findUserByKey）开始 key = " + key + "\t isAva = " + isAva + "\t size"+size);
		// 返回数据
		Result<User> result = new Result<>();
		try {
			// 用于保存查询到的用户信息
			Page<User> users = null;

			// 根据字段id进行升序排序
			Order order 	= new Order(Direction.ASC, "id"); 
			// 分页排序查询
			PageRequest pageRequest = PageRequest.of(page, size, new Sort(order));
			
			if(Tool.isNumber(key)) {
				return findUserById(new Long(key));
			}else {
				users = userService.findUserByKey(key, isAva, pageRequest);
			}
			// 如果有查询结果
			if(users != null) {
				Pages pages = new Pages(page, users.getTotalElements(), size);
				
				result.setPages(pages);
				result.setData(users.getContent());
				result.setSuccess("查询成功！");
			}else {
				result.setError("无此用户！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			e.printStackTrace();
			result.setError("发生异常错误！");
		}
		logger.info("\n 关键字查询（findUserByKey）结束 result = " + result);
		return result;
	}
}
